/*
 * Copyright 2010 Pierre Heinzerling, Uwe Janner, Patrick Wright
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// To avoid running multiple content scripts on one tab.
const ONLY_ONCE_ID = "PUBLINSKY_PREVENT_TO_RUN_TWICE_NODE";
var hotKey = null;

if (!window[ONLY_ONCE_ID])
{
	// create the special attribute.
	window[ONLY_ONCE_ID] = "RUN";
	
	// ask for the hotkey (from config):
	chrome.extension.sendRequest( 
			{getHotKey: "getHotKey"},
			function(response){
				if( response && response.message){
					hotKey = response.message;
					addEventListener("keydown", publinskyKeyHandler, true);
				}
			}
		);

	// somebody wants to know the selected text	
    chrome.extension.onRequest.addListener(
		function(request, sender, sendResponse) {
			if(request.getSelection) {
				sendResponse(
					{message: window.getSelection().toString()}
				);
			}
		}
    )
        
	function publinskyKeyHandler(evt){
		if (hotKey == evt.keyIdentifier){
			console.log("hot key " + evt.keyIdentifier + ":  send the selection text to background page, " + window.getSelection().toString());
			chrome.extension.sendRequest( 
				{url: window.location.href.toString(), title: document.title, selection: window.getSelection().toString(), key: evt.keyIdentifier},
				function(response){
                    // CLEAN: leave this in for now, for debugging
					//if( response && response.message ) alert("Message: " + response.message);
				}
			);
		}
	}

}
